<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class Account extends Model
{
    public function power(): HasOne
    {
        return $this->hasOne(Role::class, "id", "rid");
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->with(['power'])->where("is_del", 1)->order('create_time', 'desc')->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();

        return pageData($data);
    }

    public function insertData(): array
    {
        $param = request()->post();
        if (!empty($param['password'])) {
            $pwd = setPassword($param['password']);
            $param['password'] = $pwd['password'];
            $param['code'] = $pwd['token'];
        } else {
            unset($param['password']);
        }
        $count = $this->when(!empty($param['id']), function ($query) use ($param) {
            $query->where("id", "<>", $param['id']);
        })->where("account", $param['account'])->count();
        if ($count > 0) throw new \Exception('账号已存在', 7001);
        $this->startTrans();
        $this->exists(!empty($param['id']))->save($param);
        $this->commit();
        return $this->toArray();
    }
}
